/*  ----------------------------------------------------------------------------
 *  Arello Mobile
 *  Fast 3d Engine
 *  ----------------------------------------------------------------------------
 * Except where otherwise noted, this work is licensed under
 * http://creativecommons.org/licenses/by/3.0
 */

#include "ImageSimpleRep.h"

namespace liba
{
namespace lib2d
{
namespace objects
{

void ImageSimpleRep::load( const filesystem::String & image_name )
{
	if( !pl )
		pl = new pictureformat::Loader( image_name );
	if( !pl->is_ready() )
		return;
	if( !pl->is_valid() )
		throw GluckBadResource( __FUNCTION__, "picture is not valid", image_name );

	HardVector::iterator it = hard_vector.begin();
	for( ;it != hard_vector.end(); ++it )
	{
		if( it->second && it->second->is_valid() )
			continue;

		hard::Manager::hardware_type * hardware = it->first;
		pictureformat::Format hardware_format = hardware->get_associated_format( pl->get_best_format() );
		pl->reset( hardware_format );
		if( !it->second )
			it->second = hardware->create_image( pl->get_width(), pl->get_height(), hardware_format );

		hard::Image * tex = it->second;
		int stride = 0;
		void * dst = tex->lock( &stride );
		dst = reinterpret_cast<char *>(dst) + (pl->get_height() - 1) * stride;
		for( int i = 0; i != pl->get_height(); ++i )
		{
			pl->unpack_scanline( dst );
			dst = reinterpret_cast<char *>(dst) - stride;
		}
		tex->unlock();
	}
	pl = 0;
	stop_loading();
}

void ImageSimpleRep::on_add_hardware( hard::Manager::hardware_type * ha )
{
	hard_vector.push_back( SweetPair( ha, 0 ) );
	start_loading();
}

} //namespace objects
} //namespace lib2d
} //namespace liba

